package juc.work;

import java.util.concurrent.Semaphore;

public class PrintABC {

    /*
    面试题 顺序打印ABC 信号量解法
     */
    public static void main(String[] args) {
        Semaphore semaphoreA = new Semaphore(0);
        Semaphore semaphoreB = new Semaphore(0);
        Semaphore semaphoreC = new Semaphore(0);

        new Thread(() -> {
            try {
                while (true) {
                    System.out.println("a");
                    Thread.sleep(1000);
                    // 注意顺序 先V(B) 再P(A)
                    semaphoreB.release();
                    semaphoreA.acquire();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "A").start();

        new Thread(() -> {
            try {
                while (true) {
                    // p(B)
                    semaphoreB.acquire();
                    System.out.println("b");
                    Thread.sleep(1000);
                    semaphoreC.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "B").start();

        new Thread(() -> {
            try {
                while(true) {
                    semaphoreC.acquire();
                    System.out.println("c");
                    Thread.sleep(1000);
                    semaphoreA.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "C").start();
    }
}
